﻿namespace sfcms.api
{
    using System;
    using System.Data;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web;

    public class user
    {
        public long id;
        private const string SESSION_KEY = "B0EC5862-F496-4A54-A4D1-CB6430EAB702";
        public string username;

        private static byte[] HashPassword(string password)
        {
            return SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(password));
        }

        public static bool Login(string username, string password)
        {
            user userToLogIn = TryLogin(username, password);
            if (userToLogIn == null)
            {
                return false;
            }
            HttpContext.Current.Session["B0EC5862-F496-4A54-A4D1-CB6430EAB702"] = userToLogIn;
            return true;
        }

        public static user newuser(string username, string password)
        {
            return new user { id = Convert.ToInt64(new database().ExecuteScalar("INSERT INTO SFCMS_User (UserName, Password) VALUES (@0, @1)\r\nSELECT SCOPE_IDENTITY()", new object[] { "@0", username, "@1", HashPassword(password) })), username = username };
        }

        private static user TryLogin(string username, string password)
        {
            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException("userName");
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }
            DataTable dbuser = new database().ExecuteDataTable("SELECT [ID], UserName FROM SFCMS_User (NOLOCK) WHERE UserName = @0 AND Password = @1", new object[] { "@0", username, "@1", HashPassword(password) });
            if (dbuser.Rows.Count == 0)
            {
                return null;
            }
            return new user { username = username, id = Convert.ToInt64(dbuser.Rows[0]["ID"]) };
        }

        public static user current
        {
            get
            {
                if ((HttpContext.Current == null) || (HttpContext.Current.Session == null))
                {
                    return null;
                }
                return (HttpContext.Current.Session["B0EC5862-F496-4A54-A4D1-CB6430EAB702"] as user);
            }
        }
    }
}

